package com.fingard.dsp.bank.directbank.gdb01.receiptPro;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.cgb02.CGB02Base;
import com.fingard.dsp.bank.directbank.gdb01.GDB01Base;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.task.DelayCounter;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.FGBiz;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

/**
 * @Description TODO
 * @Author xtt
 **/
public class GDB01TaskReceiptpro extends GDB01Base {
    private String logCode = "GDB01"+ File.separator+"TaskReceiptPro";
    private TaskTimerSet timerSet;
    private ReceiptProConfig proConfig;
    //private boolean byLocalhost;

    private static DelayCounter delayCounter = new DelayCounter(45, 2);//最大延时45分钟，按平方计算，即4次=4*4=16分钟
    public static void resetDelayCounter(){
        delayCounter.resetZeroCount();
    }

    public void downReceipt(TaskTimerSet pTimerSet){
        try {
            timerSet = pTimerSet;

            proConfig = ReceiptPro.getReceiptProConfig();
            //byLocalhost = false;
            downlaodForSftpAndInsert();

        } catch (Exception e) {
            FGBiz.logTrace.exception(logCode, e);
        }
    }

    /**
     * sftp方式回单获取
     *
     * @return
     */
    public void downlaodForSftpAndInsert() throws IOException {

        SftpPortClient sftpPortClient = null;
        String saveDirPathTemp = proConfig.localSaveMainDir;
        String qryDay8 = Format.Date8Format.format(new Date());
        try {
            FtpSet ftpSet = bankFront.getFtpSet("receipt");
            ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/") + "/";
            WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
            WriteBankLogLn("开始遍历服务器文件目录" + ftpSet.downDir + qryDay8);

            sftpPortClient = new SftpPortClient(ftpSet);
            ArrayList<String> ftpFileList = sftpPortClient.listNames(ftpSet.downDir + qryDay8);
            if (ftpFileList.size() == 1) {
                WriteBankLogLn("当前日期："+qryDay8+"无回单文件");
                FGBiz.logTrace.info(logCode,"当前日期："+qryDay8+"无回单文件");
            }

            FtpReceiver ftpReceiver = sftpPortClient.downloadFile(ftpSet.downDir + qryDay8,saveDirPathTemp);
            File tmpFile = new File(saveDirPathTemp) ;
            File[] files = tmpFile.listFiles();
            int[] retVals = new int[3];
            retVals[0] = 0;//总pdf个数
            retVals[1] = 0;//新增
            retVals[2] = 0;//已存在
            for (File file : files) {
                String ftpFileName = file.getName();
                if (ftpFileName.contains(".txt")) {
                    WriteBankLogLn("解析汇总文件:" + ftpFileName);
                    //保存路径
                    if (ftpReceiver.isCompleted) {

                        //解析汇总文件返回map
                        String[] line = FileHelper.readFileText(saveDirPathTemp,"UTF-8").split("\n|\r");
                        int totalFiles = 0;
                        //读取文件内容
                        for (String pfiles : line) {
                            if(!pfiles.contains("\\|")){
                                totalFiles = Integer.valueOf(pfiles);
                            }else{
                                //入库
                                String[] receiptInfo = pfiles.split("\\|");
                                ReceiptData eachData = new ReceiptData();
                                eachData.bank = "307";
                                eachData.srcSys = "CGB02";
                                if(receiptInfo[4].contains("D")){
                                    eachData.moneyWay = "1";
                                }else if(receiptInfo[4].contains("C")){
                                    eachData.moneyWay = "2";
                                }
                                eachData.downState = "2";
                                eachData.downTime = new Date();
                                eachData.bnkSeqNo = receiptInfo[1];
                                eachData.receiptNo = receiptInfo[1];
                                eachData.oppActNum = receiptInfo[5];
                                eachData.ownAct = receiptInfo[0];
                                ReceiptDataHelper receiptHelper = new ReceiptDataHelper(reqHeader.tenant, eachData.getBusDate());
                                int inRe = receiptHelper.insertIfNotExist(eachData, true);
                                if(inRe>0){
                                    retVals[1] = retVals[1] + 1;
                                }else if(inRe == 0){
                                    retVals[2] = retVals[2] + 1;
                                }
                                WriteBankLogLn(eachData.receiptNo+"写入数据库，影响行数："+inRe);
                                FGBiz.logTrace.info(logCode, eachData.receiptNo+"写入数据库，影响行数："+inRe);

                            }
                        }
                    } else {
                        WriteBankLogLn(ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                        FGBiz.logTrace.error(logCode, ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            WriteBankLogLn(ex);
        } finally {
            if (sftpPortClient != null) {
                sftpPortClient.disconnect();
            }
        }

    }
}
